package com.bbc.yuntun.platform.interceptor;

import com.alibaba.fastjson2.JSON;
import com.bbc.yuntun.common.constant.HttpStatus;
import com.bbc.yuntun.common.core.domain.R;
import com.bbc.yuntun.common.utils.ServletUtils;
import com.bbc.yuntun.common.utils.StringUtils;
import com.bbc.yuntun.platform.domain.model.WxLoginUser;
import com.bbc.yuntun.platform.service.wx.WxTokenService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Nonnull;
import java.util.Objects;


/**
 * 小程序鉴权拦截器
 *
 * @author liac
 * @date 2022/10/14 16:48
 */
@Component
public class WxAuthInterceptor implements HandlerInterceptor {

    @Resource
    private WxTokenService wxTokenService;

    /**
     * 拦截预处理
     *
     * @param request HTTP请求
     * @param response HTTP响应
     * @param handler 处理器
     * @return 拦截结果
     */
    @Override
    public boolean preHandle(@Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response, @Nonnull Object handler) {
        //如果token
        WxLoginUser loginUser = wxTokenService.getLoginUser(request);
        //如果用户不为空，并且token即将过期，则自动刷新令牌有效期
        if (Objects.nonNull(loginUser)) {
            wxTokenService.verifyToken(loginUser);
            return true;
        }
        String msg = StringUtils.format("请求访问：{}，微信认证失败，无法访问系统资源", request.getRequestURI());
        ServletUtils.renderString(response, JSON.toJSONString(R.fail(HttpStatus.UNAUTHORIZED, msg)));
        return false;
    }

}
